package com.highspeed.bdk.bean.base;

/**
 * @program: bdk-service
 * @description:
 * @author: Chenjiabin
 * @create: 2018-04-22 20:29
 **/

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Collection;

public class LocalUserDetails extends User {
    private String id;
    private String name;
    private String email;

    public LocalUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
        this.checkAndUpdateRoles();
    }

    public LocalUserDetails(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.checkAndUpdateRoles();
    }

    public LocalUserDetails(String id, String name, String email, String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends SimpleGrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.id = id;
        this.name = username;
        this.email = email;
        this.checkAndUpdateRoles();
    }

    private void checkAndUpdateRoles() {
        for (GrantedAuthority authority : this.getAuthorities()) {
            if (!authority.getAuthority().startsWith("ROLE_")) {
                Field field = ReflectionUtils.findField(authority.getClass(), "role");
                if (field != null) {
                    field.setAccessible(true);
                    ReflectionUtils.setField(field, authority, "ROLE_" + authority.getAuthority());
                }
            }
        }
    }
}
